package game.userinteraction;

import java.awt.event.ActionEvent;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.Action;
import javax.swing.KeyStroke;


/**
 * This class allows a user to define how an object will be
 * controlled by the user. Based on that definition, this
 * class will call the necessary methods in the program,
 * depending on what buttons/keys the user has pressed.
 * 
 * @author Paul
 * @author rwb10
 * 
 */
public class UserInputBehavior implements IControllable {

    private Map<KeyStroke, Action> myKeyBindings;
    private Object myObject;
    private ActionEvent myActionEvent;

    /**
     * Creates a new UserInputBehaviorClass that will
     * automatically call a specified Object's methods
     * when a key is pressed.
     * 
     * @param toInfluence The Object's whose methods
     *        will be called.
     */
    public UserInputBehavior(Object toInfluence) {
        myObject = toInfluence;
    }

    /**
     * Creates a UserInputBehaviorClass that will automatically
     * call a specified Object's methods.
     * 
     * @param toInfluence The Object whose methods will be called
     *        when a relevant key is pressed.
     * @param e An ActionEvent that can be used to alter how
     *        the Method calls to the Object parameter occur.
     */
    public UserInputBehavior(Object toInfluence, ActionEvent e) {
        myObject = toInfluence;
        myActionEvent = e;
    }

    /**
     * Determines how the Methods called by this class will occur.
     * 
     * @param e The Object that will be used when a relevent key
     *        is pressed.
     */
    public void setActionEvent(ActionEvent e) {
        myActionEvent = e;
    }

    /**
     * Sets up a mapping of key presses to Methods, based on the
     * specification of a ResourceBundle.
     * 
     * @param keyControlManual The ResourceBundle that will define
     *        which key presses do what.
     * @throws SecurityException Exception.
     * @throws NoSuchMethodException Exception.
     */
    public void defineKeyBindings(ResourceBundle keyControlManual)
            throws SecurityException, NoSuchMethodException {
        GameControlReader controlReader = new GameControlReader(
                keyControlManual, myObject);
        myKeyBindings = controlReader.getKeyBindings();
    }

    @Override
    public void react(Set<KeyStroke> keyPresses) {
        for (KeyStroke stroke : keyPresses) {
            if (myKeyBindings != null && myKeyBindings.get(stroke) != null) {
                myKeyBindings.get(stroke).actionPerformed(myActionEvent);
            }
        }
    }

}
